<?php
/**
 * Url:http://localhost/webapp/?r=category
 * 
 * Model
 * 
 * application/components/Controller
 * 
 * @author Elwin
 *
 */
class CategoryController extends Controller {
	/*
	public function actions(){
		// return external action classes, e.g.:
		return array(
				'authlog'=>'application.controllers.authentication.LoginAction',
				// page action renders "static" pages stored under 'protected/views/site/pages'
				// They can be accessed via: index.php?r=site/page&view=FileName
				'page'=>array(
						'class'=>'CViewAction',
				),
		);
	}*/
	
	/**
	 */
	public function init() {
		parent::init ();
		// $this->load();
		if (! Yii::app ()->request->isAjaxRequest) {
			// 当在ajax请求时，不需要加载的css js文件
			$cs = Yii::app ()->clientScript;
			$cs->scriptMap = array (
					// 将两个js合并成一个文件输出
					'jquery.js' => '/js/all.js',
					'jquery.ajaxqueue.js' => '/js/all.js' 
			);
			
			Yii::app ()->clientScript->scriptMap = array (
					Yii::app ()->baseUrl . '/jscript/common.js' => true 
			);
			// print_r(Yii::app()->baseUrl);
			// Yii::app ()->clientScript->registerScriptFile ( Yii::app
			// ()->baseUrl . "/jscript/common.js" );
		}
		// 控制器动作中关闭输出：
		foreach (Yii::app()->log->routes as $route)
			 $route->enabled=false;
		
	}
	public function actionCreate() {
		$this->render ( 'create', array () );
	}
	public function actionUpdate() {
	}
	public function actionList() {
		$sql = 'SELECT * FROM ' . Category::model ()->tableName () . ' ORDER BY sort DESC';
		$command = Yii::app ()->db->createCommand ( $sql );
		$categories = $command->queryAll ();
		// print_r($categories);
		$category = new Category (); // array('order'=>'sort ASC')
		$category = Category::model ()->findAll ( array (
				'order' => 'sort ASC' 
		) );
		// print_r($model->getData());
		// foreach($model as $value){
		// print_r($value->catename);
		// }
		$this->render ( 'list', array (
				'category' => $category 
		) );
	}
	
	/*
	 * http://localhost/webapp/?r=category
	 */
	public function actionIndex() {
		$data = array (
				0 => array (
						'id' => 1,
						'pid' => 0,
						'name' => 'name1' 
				),
				1 => array (
						'id' => 2,
						'pid' => 0,
						'name' => 'name2' 
				),
				2 => array (
						'id' => 3,
						'pid' => 1,
						'name' => 'name3' 
				),
				3 => array (
						'id' => 4,
						'pid' => 3,
						'name' => 'name4' 
				) 
		);
		// {Normal Cache}
		
		// print_r(Yii::app()->cache); //check the value
		$cache = Yii::app ()->filecache;
		$time = $cache->get ( 'BoyLee001' ); // get cache
		if (false === $time) { // if cache is gone.
			$cache->set ( 'BoyLee001', time (), 30 );
			// set cache $cache['BoyLee001'] = $time();
			// this is not right.
			$time = $cache->get ( 'BoyLee001' );
		}
		// echo $time;
		
		$category = new Category ();
		$setting = array (
				'idKey' => 'id',
				'pidKey' => 'pid',
				'nameKey' => 'name',
				'rootPid' => '0' 
		);
		// $category->initialized ( $setting, $data );
		
		$chtmlTree = new CHtmlTree ();
		
		// $tree = $category->getBranch ( $data );
		
		// echo '<pre>';
		// print_r ( $tree );
		// print_r ( $category->printTree($tree));
		// $category = $category->findByPk(1);
		// $category->item = 'xx';
		// print_r ( $category->getName ( 'XXXXXXX' ) );
		// echo "<BR>\$category->hidden:";
		// print_r($category->getHidden());
		// print_r ( $category->hidden );
		// Position::model ()->getCache ();
		// echo "<BR>\$category->hidden:";
		// echo $category->hidden . "\n";
		
		// $data = $tree->iniData ( new Position () );
		// $data = $tree->buildTree ( $data );
		// echo 'xxxxx:' . Position::model ()->getdd ();
		// echo "<pre>";
		// print_r ( $data );
		// WArray::isEmpty ( $list );
		
		$this->render ( 'index' );
	} // fregment cache
	
	/**
	 * {Fregment Cache} 碎片缓存
	 */
	public function actionFregmentCache() {
		if ($this->beginCache ( 'BoyLee002', array (
				'duration' => 60,
				'dependency' => array (
						// you must have db set here
						'class' => 'system.caching.dependencies.CDbCacheDependency',
						'sql' => 'SELECT COUNT(*) FROM  `user`' 
				),
				// you must have db set here cache by $_GET['id']
				'varyByParam' => array (
						'id' 
				) 
		) )) {
			echo 'BoyLee' . time ();
			echo @$_GET ['id'];
			echo ' <hr /> ';
			$this->endCache ();
		}
	}
	/*
	 * {PageCache} {controller}
	 */
	public function filters() {
		return array (
				array (
						'COutputCache + PageCache',
						'duration' => 30,
						'varyByParam' => array (
								'id' 
						) 
				) 
		);
	}
	public function actionPageCache() {
		$this->render ( 'pageCache' );
	}
	
	/**
	 * Shows a particular model.
	 */
	public function actionShow() {
		if (isset ( $_GET ['id'] ))
			$id = $_GET ['id'];
		else
			$id = Yii::app ()->session ['business_id'];
		if (! isset ( $id ) || $id == null)
			return;
		
		$model = $this->loadBusiness ( $id ); // 鍘傚晢淇℃伅
		
		$sql = "select name from business_sorts where FIND_IN_SET(code,'" . implode ( ',', $model->product_sort ) . "')";
		$sort_models = Business_sorts::model ()->findAllBySql ( $sql );
		
		$criteria = new CDbCriteria (); // 浜у搧淇℃伅
		$criteria->select = 'product.*,areas.name as area_name,city.name as city_name,province.name as province_name';
		$criteria->join = 'INNER JOIN business ON business.id=product.fk_business_id
						 INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code';
		$cond = 'product.state=0';
		if (isset ( Yii::app ()->session ['business_id'] ))
			$cond .= ' and product.fk_business_id=' . Yii::app ()->session ['business_id'];
		$criteria->addCondition ( $cond );
		$criteria->addCondition ( 'product.fk_business_id=' . $id );
		
		$pages = new CPagination ( Product::model ()->count ( $criteria ) );
		$pages->pageSize = Yii::app ()->params ['page_size'] ['user_product_in_business'];
		$pages->applyLimit ( $criteria );
		$product_models = Product::model ()->findAll ( $criteria );
		
		$this->render ( 'show', array (
				'model' => $model,
				'product_models' => $product_models,
				'pages' => $pages,
				'sort_models' => $sort_models 
		) );
	}
	public function actionSearch_by_sort() {
		$this->pageTitle = Yii::app ()->name . '-鍘傚鍒嗙被鎼滅储';
		if (isset ( $_POST ['product_sort'] ))
			$_GET ['product_sort'] = $_POST ['product_sort'];
		if (! isset ( $_GET ['product_sort'] ))
			return;
		$product_sort = $_GET ['product_sort'];
		
		$sql = "select code,name from business_sorts where code='" . substr ( $product_sort, 0, 2 ) . "' or code='$product_sort' order by code";
		$sort_models = Business_sorts::model ()->findAllBySql ( $sql );
		
		$criteria = new CDbCriteria ();
		$criteria->select = 'business.*,areas.name as area_name,city.name as city_name,province.name as province_name,count(product.id) as product_sum';
		$criteria->join = 'INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code
						 LEFT JOIN product ON product.fk_business_id=business.id and product.state=0';
		
		$criteria->addCondition ( 'FIND_IN_SET("' . $product_sort . '", business.product_sort)>0' );
		$criteria->addCondition ( 'business.state=0' );
		$criteria->group = 'business.id';
		$criteria->order = 'business.recommend2 desc,business.update_time desc';
		
		$model = Business::model ();
		$command = $model->getCommandBuilder ();
		$sql = "select count(t.id) from( select business.id FROM business";
		$sql = $command->applyJoin ( $sql, $criteria->join );
		$sql = $command->applyCondition ( $sql, $criteria->condition );
		$sql = $command->applyGroup ( $sql, $criteria->group ) . ") as t"; // echo $sql;
		$pages = new CPagination ( $model->countBySql ( $sql, $criteria->params ) );
		$pages->pageSize = Yii::app ()->params ['page_size'] ['search_business_by_sort'];
		$pages->applyLimit ( $criteria );
		
		$sort = new CSort ( 'Business' );
		$sort->applyOrder ( $criteria );
		
		$models = $model->findAll ( $criteria );
		
		$this->render ( 'search_by_sort', array (
				'models' => $models,
				'pages' => $pages,
				'sort' => $sort,
				'sort_name' => $sort_models 
		) );
	}
	/**
	 * http://logisticsfortest.googlecode.com/svn-history/r722/jj360/protected/controllers/BusinessController.php
	 */
	public function actionSearch_by_brand()
	{
		if(isset($_POST['b_name']))$_GET['b_name']=$_POST['b_name'];
		if(!isset($_GET['b_name'])) return;
		$b_name=trim($_GET['b_name']);
	
		$criteria=new CDbCriteria;
		$criteria->select='business.*,areas.name as area_name,city.name as city_name,province.name as province_name,count(product.id) as product_sum';
		$criteria->join='INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code
						 LEFT JOIN product ON product.fk_business_id=business.id and product.state=0';
	
		if(isset($b_name)&&$b_name!='')
			$criteria->addCondition('business.brand like "%'.$b_name.'%"');
		$criteria->addCondition('business.state=0');
		$criteria->group='business.id';
		$criteria->order='business.recommend2 desc,business.update_time desc';
	
		$model=Business::model();
		$command=$model->getCommandBuilder();//鍥爂roup by 鏌ヨ鍑嗙‘璁板綍鏁伴噺
		$sql="select count(t.id) from( select business.id FROM business";
		$sql=$command->applyJoin($sql,$criteria->join);
		$sql=$command->applyCondition($sql,$criteria->condition);
		$sql=$command->applyGroup($sql,$criteria->group).") as t";//echo $sql;
		$pages=new CPagination($model->countBySql($sql,$criteria->params));
		$pages->pageSize=Yii::app()->params['page_size']['search_business_by_area'];
		$pages->applyLimit($criteria);
	
		$sort=new CSort('Business');
		$sort->applyOrder($criteria);
	
		$models=$model->findAll($criteria);
	
		$this->render('search_by_brand',array(
				'models'=>$models,
				'pages'=>$pages,
				'sort'=>$sort,
				'b_name'=>$b_name
		));
	}
}
?>